package com.dhh.sky.activity;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import com.dhh.sky.SDAApplication;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveDownloadOperation;
import android.app.IntentService;
import android.content.Intent;
import android.os.Environment;

public class DownloadMessageService extends IntentService {
	public static final String DOWNLOAD_PROGRESS = "DOWNLOAD_PROGRESS";
	private LiveConnectClient mClient;

	public DownloadMessageService() {
		super("DownloadMessageService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		String id = intent.getExtras().getString("id");
		String source = intent.getExtras().getString("source");
		String name = intent.getExtras().getString("name");
		doDownload(id,source,name);
	}
	
	private void doDownload(String id,String source,final String name){        
        mClient = ((SDAApplication) getApplication()).getConnectClient();
        try {
        	LiveDownloadOperation operation = mClient.download(source);
        	File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/SkyDrive");
			if(!dir.exists()) dir.mkdir();										
			File file = new File(Environment.getExternalStorageDirectory().getPath()+"/SkyDrive/"+name);
			if(file.exists()){
				file.delete();
				file.createNewFile();
			}
			InputStream input = new BufferedInputStream(operation.getStream());							
			int aSize = operation.getContentLength();
            OutputStream output = new BufferedOutputStream(new FileOutputStream(file));

            byte data[] = new byte[operation.getContentLength()/10];
            long total = 0;
            int count;
            int current = 10;
            sendProgress(id,0);
            while ((count = input.read(data)) != -1) {
                total += count;							               
                output.write(data, 0, count);    				                
                
                int percentCompleted = computePrecentCompleted(aSize, aSize-total);
				if(percentCompleted>=current || percentCompleted==100){
					current +=10;
					int progress =  current;
					if(progress>100) progress = 100;
					sendProgress(id,progress);
				}                
            }

            output.flush();
            output.close();
            input.close();            
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}
	
	private int computePrecentCompleted(long totalBytes, long bytesRemaining) {
        return (int) (((float)(totalBytes - bytesRemaining)) / totalBytes * 100);
    }
	
	private void sendProgress(String id, int current){
		Intent intent = new Intent("download");
		intent.putExtra("id", id);
		int progress =  current;
		if(progress>100) progress = 100;
		intent.putExtra("current", progress);
		sendBroadcast(intent);
	}
}
